<template>
  <div class="app-container">
    <!-- “添加”等标题栏 -->
    <div class="filter-container add1">
      <el-form style="">
        <el-form-item>
          <!-- 按钮级别的控制,使用hasPerm来判断是否应该有添加这个按钮 -->
          <el-button type="primary" icon="plus" @click="showCreate" v-if="hasPerm('article:add')">添加
          </el-button>

          <!-- 下载模板 -->
          <el-button @click="exportExcel" type="primary" icon="plus" v-if="hasPerm('article:add')">下载导入模板
          </el-button>
						<!-- 使用后端导入 -->
            
            <el-button type="primary" icon="plus" v-if="hasPerm('article:add')" size="small">导入
              <input type="file" id = "btn" ref="clearFile" name = "file" @change="importf(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
          </el-button>
            
          <el-button @click="exportExcelOpertor" type="primary" icon="plus" v-if="hasPerm('article:add')" >导出</el-button>
          <el-button @click="showDisplay" type="primary" icon="plus" >显示字段</el-button>
          <!-- <el-button @click="exportExcel" type="primary" icon="plus" v-if="hasPerm('article:add')" >导出</el-button> -->
           <el-button type="danger" v-if="multipleSelectionFlag" @click="delSelect">
              批量删除
          </el-button>
          <!--
           <el-button type="primary" icon="plus" @click="showUserInfo" v-if="hasPerm('article:add')">添加
          </el-button>
          -->
        </el-form-item>
      </el-form>
      
    </div>

    <!-- “搜索”栏 -->
    <div class="searchWord">
      <!-- style="display: inline-block;"  -->
        <el-input v-model="search" 
          placeholder="请输入搜索内容" @input="inputFunction()">
        </el-input>
      </div>
    <br>
    <el-table class="tabless" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
              highlight-current-row :row-class-name="tableRowClassName" @sort-change='sortChange' @selection-change="handleSelectionChange">
              <el-table-column
      type="selection"
      width="55"
      v-if="displayItem.select">
    </el-table-column>
      <el-table-column align="center" label="序号" width="80" v-if="displayItem.id">
        <template slot-scope="scope">
          <!-- 文章的索引 -->
          <span v-text="getIndex(scope.$index)"> </span>
          <!-- 文章的id -->
          <!-- <span v-text="scope.row.id"> </span> -->
        </template>
      </el-table-column>
      <!-- 表格主要列名称 -->
      <!-- 添加排序sortable='custom' sortable='customsss' -->
      <el-table-column align="center" prop="department_id" label="部门编号" style="width: 60px;" v-if="displayItem.code"></el-table-column>
      <el-table-column align="center" prop="department_name" label="部门名称" style="width: 60px;" v-if="displayItem.name"></el-table-column>
      <el-table-column align="center" prop="department_desc" label="部门描述" style="width: 60px;" v-if="displayItem.content"></el-table-column>
      <el-table-column align="center" prop="staff_id" label="主管工号" style="width: 60px;" v-if="displayItem.staffId"></el-table-column>
      <el-table-column align="center" prop="superior_id" label="上级部门编号" style="width: 60px;" v-if="displayItem.superiorId"></el-table-column>
      <el-table-column align="center" prop="create_staff_id" label="创建人编号" style="width: 60px;" v-if="displayItem.createStaffId"></el-table-column>
      <el-table-column align="center" prop="update_staff_id" label="更新人编号" style="width: 60px;" v-if="displayItem.updateStaffId"></el-table-column>
      <el-table-column align="center" prop="update_time" label="更新时间" style="width: 60px;" v-if="displayItem.updateTime"></el-table-column>
      <el-table-column align="center" label="创建时间" width="170" prop = "create_time" v-if="displayItem.createTime">
        <!-- <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template> -->
      </el-table-column>

      <el-table-column align="center" label="管理" width="200" v-if="hasPerm('article:update') & displayItem.manageMent">
        <template slot-scope="scope">
          <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)">修改</el-button>
          <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 以上为主界面内容 -->

    <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow" >确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisibleByBatch" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定批量删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisibleByBatch = false">取 消</el-button>
                <el-button type="primary" @click="delAll" >确 定</el-button>
            </span>
        </el-dialog>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum" 
      :page-size="listQuery.pageRow"
      :total="totalCount"
      :page-sizes="[3, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination">
    </el-pagination>

    
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" >
      <el-form class="small-space" :model="tempDepartment" label-position="left" label-width="120px"
               style='width: 400px; margin-left:50px;'>
        
        <!-- “添加”功能弹出界面 -->
        <el-form-item label="部门名称" required v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-input type="text" v-model="tempDepartment.departmentName" @keyup.native = "handlerDepartment"></el-input>
          <el-tag type="danger" v-if="this.displayInfoFromBack">{{infoFromBack}}</el-tag>          
        </el-form-item>
        <el-form-item label="部门描述" required v-if="dialogStatus=='create' | dialogStatus=='update'">
          <el-input type="textarea" v-model="tempDepartment.departmentDesc"></el-input>
        </el-form-item>

        <el-form-item label="主管人" required v-if="dialogStatus=='create' | dialogStatus=='update'">
         <!-- 暂时不用 -->
         <el-select v-model="tempDepartment.staffId" placeholder="请选择" v-if="textMap[dialogStatus] == '详细信息'" :disabled="true">
            <el-option
              v-for="item in staffList"
              :key="item.userId"
              :label="item.username"
              :value="item.userId">
            </el-option>
          </el-select>
          <!-- 添加对话框 -->
          <!--
          <el-select v-model="tempDepartment.staffId" placeholder="请选择" v-if="dialogStatus=='create' | dialogStatus=='update'" :disabled="false">
            <el-option
              v-for="item in staffList"
              :key="item.userId"
              :label="item.username"
              :value="item.userId">
            </el-option>
          </el-select> -->

          <!-- 提供实时匹配 -->
          <el-row class="demo-autocomplete" placeholder="请搜索并选择" v-if="dialogStatus=='create' | dialogStatus=='update'" >
          <el-col :span="30">
            <el-autocomplete class="inline-input" v-model="tempDepartment.staffNickname" :fetch-suggestions="querySearch" @select="handleSelect"></el-autocomplete>
          </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="上级部门编号" required v-if="dialogStatus=='create' | dialogStatus=='update'">
         <!-- 暂时不用 -->
         <el-select v-model="tempDepartment.superiorId" placeholder="请选择" v-if="textMap[dialogStatus] == '详细信息'" :disabled="true">
            <el-option
              v-for="item in departmentList"
              :key="item.department_id"
              :label="item.department_name"
              :value="item.department_id">
            </el-option>
          </el-select>
          <!-- 添加对话框 -->
          <el-select v-model="tempDepartment.superiorId" placeholder="请选择" v-if="dialogStatus=='create' | dialogStatus=='update'" :disabled="false" style='width: 283px'>
            <el-option
              v-for="item in departmentList"
              :key="item.department_id"
              :label="item.department_name"
              :value="item.department_id">
            </el-option>
          </el-select>
        </el-form-item>


        <!-- “显示字段”功能弹出界面 -->
        <div v-if="dialogStatus=='dispalyAtt'">
          <el-checkbox v-model="displayItem.select">复选框</el-checkbox><br>
          <el-checkbox v-model="displayItem.id">序号</el-checkbox><br>
          <el-checkbox v-model="displayItem.code">部门编号</el-checkbox><br>
          <el-checkbox v-model="displayItem.name">部门名称</el-checkbox><br>
          <el-checkbox v-model="displayItem.content">部门描述</el-checkbox><br>
          <el-checkbox v-model="displayItem.staffId">主管工号</el-checkbox><br>
          <el-checkbox v-model="displayItem.superiorId">上级部门编号</el-checkbox><br>
          <el-checkbox v-model="displayItem.createStaffId">创建人编号</el-checkbox><br>
          <el-checkbox v-model="displayItem.updateStaffId">更新人编号</el-checkbox><br>
          <el-checkbox v-model="displayItem.updateTime">更新时间</el-checkbox><br>
          <el-checkbox v-model="displayItem.createTime">创建时间</el-checkbox> <br>
          <el-checkbox v-model="displayItem.manageMent">管理</el-checkbox>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createDepartment" :disabled="enableCreate">创 建</el-button>
        <el-button type="primary" v-if="dialogStatus=='update'" @click="updateDepartment">修 改</el-button>
        
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import FileSaver from "file-saver";
  import XLSX from "xlsx";
  import {mapGetters} from 'vuex';
  export default {
    data() {
      return {
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageRow: 5,//每页条数
          name: ''
        },
        staffList: [], //所有人员数据，用于下拉菜单(已用实时搜索替代)
        departmentList: [], //所有部门数据，用于下拉菜单
        // 为textMap中的属性,指定标题头
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '创建部门',
          dispalyAtt: '显示字段'
        },
        //该对象组织前端页面信息，传到后台
        tempDepartment: {
          //id: "",
          //content: "",
          departmentId: "",
          departmentName: "",  
          departmentDesc: "",  
          staffId: "",     
          superiorId: "",
          loginUserId: "",
          staffNickname: ""
        },
        delVisible:false,//删除提示弹框的状态
        delVisibleByBatch:false,//批量删除提示弹框的状态
        msg:"",//记录每一条的信息，便于取id
        delarr:[],//存放删除的数据
        multipleSelection:[],//多选的数据
        // 搜索框中的内容
        search:'',
        // 排序的列名
        prop:'',
        // 排序的方式:包括asc,desc等
        order:'',
        // 记录导出得时候跳页的之前的页数
        temp_page:3,

        //实时匹配输入数据（实时从后台返回来的数据)
        infoFromBack:'',
        displayInfoFromBack:false, //填写表单实时查重后提示
        enableCreate:false,

        //实时搜索用户输入
        staffList2: [],
        //state1: '',
        // 实时搜索结束 

        multipleSelectionFlag : true,
        // 记录显示字段
        displayItem:{
          select:true,
          id:true,
          code:true,
          name:true,
          content:true,
          //staffId:flase,
          //superiorId:flase,
          //createStaffId:flase,
          //updateStaffId:flase,
          //updateTime:flase,
          //createTime:true,
          manageMent:true
        }
      }
    },
    computed: {
      ...mapGetters([
        'userId',
        'nickname'
      ])
    },
    created() {
      this.getList();
      if (this.hasPerm('user:add') || this.hasPerm('user:update')) {
        this.getAllUsers();
      }
      if (this.hasPerm('department:add') || this.hasPerm('department:update')) {
        this.getAllDepartments();
      }
    },
    methods: {
      clearFile() {
        this.$refs.clearFile.value = ''; // 清空file文件
      },
      showUserInfo(){
        console.log("id:",this.userId);
        console.log("nickname:",this.nickname);
      },
      // 导入
      importf(obj) {
        let _this = this;
        let inputDOM = this.$refs.inputer;   // 通过DOM取文件数据
        this.file = event.currentTarget.files[0];  
        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;
        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
              var bytes = new Uint8Array(reader.result);
              var length = bytes.byteLength;
              for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
              }
              var XLSX = require('xlsx');
              if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                        type: 'base64'
                  });
              } else {
                  wb = XLSX.read(binary, {
                        type: 'binary'
                  });
              }
              // outdata就是你想要的东西 excel导入的数据
              outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); 
              // excel 数据再处理
              let arr = []
              outdata.map(v => {
                  // console.log(v)
                  let obj = {}
                  obj.content = v.内容
                  obj.id = ""
                  arr.push(obj)
                  _this.tempDepartment = obj
                  console.log(_this.tempDepartment)
                  _this.createDepartment()
                  // this.api({
                  //   url: "/article/addArticle",
                  //   method: "post",
                  //   data: obj
                  // }).then(() => {
                  //   this.getList();
                  //   // this.dialogFormVisible = false
                  // })
              })
              _this.accountList = [...arr];
              console.log( _this.accountList)
              // _this.reload();
              // console.log('uuuuuuuuuuuuuuuuuuuuu');
            }
            alert("上传完毕！")
            _this.clearFile()
            reader.readAsArrayBuffer(f);
        }
        if(rABS) {
              reader.readAsArrayBuffer(f);
        } else {
              reader.readAsBinaryString(f);
        }
    },

      // 导入结束
    exportExcelOpertor(){
      // let tempPageSize = this.listQuery.pageRow;
      // alert(tempPageSize);
      // this.exportExcel();
      this.temp_page = this.listQuery.pageRow;
      console.log(this.totalCount)
      // this.listQuery.pageRow = this.totalCount;
      this.handleSizeChange(this.totalCount)
      // this.listQuery.pageRow = this.totalCount;
      // alert("1")
      // this.exportExcel();
      
      
      // alert("2")
      // this.exportExcel();
      window.setTimeout(this.exportExcel,50);
      // alert("3")
      // window.setTimeout("")
      window.setTimeout(this.delayTime,200);
    },
    delayTime(){
      this.listQuery.pageRow = this.temp_page
      this.generalFun();
    },
                  exportExcel () {
                    // alert("exportExcel")
                    // 设置当前日期
                    let time = new Date();
                    let year = time.getFullYear();
                    let month = time.getMonth() + 1;
                    let day = time.getDate();
                    let name = year + "" + month + "" + day;
                    // alert(this.totalCount);
                    
                    // alert(this.listQuery.pageRow);
                    // this.listQuery.pageNum = 1;
                    // this.getList();
                    // alert("zandaoguang");
                    // return
                    this.$nextTick(function () {
                        // alert("iiiiiiiiiiiiiiiii");
                        // alert(tempPageSize);
                        let wb = XLSX.utils.table_to_book(document.querySelector('.tabless'));
                        /* get binary string as output */
                        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
                        try {
                            FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), name + ".xlsx")
                        } catch (e) {
                            if (typeof console !== 'undefined') console.log(e, wbout)
                        }
                        // this.listQuery.pageRow = 3;//表格还原
                        // this.getList();
                        return wbout
                    }
                    )
                },
                
                
            inputFunction(){
              // console.log('zandaoguang');
              console.log(this.search);
              console.log(this.search == "");
              
              if(this.search){
                // console.log('aaaaaaaaaaaaaaaa');
                this.getListBySearch(this.search);
              }
              if(this.search == ""){
                this.getList();
              }
            },
            sortChange(column, prop, order) {

              // this.handleCurrentChange(1);
              this.listQuery.pageNum = 1;
              // 点击排序按钮后拿到column.order，可以发送column.order给后台，后台再根据什么排序来返回排序过后的数据
              // console.log(column);
              // console.log(column + '---' + column.prop + '---' + column.order)
              // this.prop = column.prop;
              // this.order = column.order;
              // console.log(this.prop);
              // console.log(column.prop);
              // console.log(this.order);
              // 如果搜索框中没有搜索内容
              if(this.search == ""){
                  if(column.order === "descending"){
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'DESC';
                    // this.prop = column.prop;
                    // this.order = 'DESC';
                  }else{
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'ASC';
                    // this.prop = column.prop;
                    // this.order = 'ASC';
                  }
                  if(column.prop == "content"){
                      this.getListByOrderContent();
                      // this.prop = '';
                      // this.order = '';
                  }
                  else if(column.prop == "createTime") {
                    this.getListByOrderCreateTime();
                    // this.prop = '';
                    // this.order = '';
                  }
                  else{
                    // 默认返回id排序
                    this.getList();
                  }
              }
              // 如果搜索框中有搜索内容
              else{
                  if(column.order === "descending"){
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'DESC';
                    // this.prop = column.prop;
                    // this.order = 'DESC';
                  }else{
                    this.listQuery.sortby = column.prop;
                    this.listQuery.order = 'ASC';
                    // this.prop = column.prop;
                    // this.order = 'ASC';
                  }
                  if(column.prop == "content"){
                    this.getListByContentHaveSearch();
                    // this.prop = '';
                    // this.order = '';
                  }
                  else if(column.prop == "createTime")  {
                    // 当空格的时候，应该怎么排序
                    // this.getListByOrderCreateTime();
                    // 默认按照id排序
                    // this.getListBySearch(this.search);
                    this.getListByOrderCreateTimeHaveSearch();
                    // this.prop = '';
                    // this.order = '';
                  }else{
                    // 默认什么都不做
                    // 默认返回id排序
                    this.getListBySearch(this.search);
                  }
              }
              //输出的结果 [object Object]---name---ascending
            },
            //单行删除
            handleDelete(index, row) {
              console.log("index:"+index);
              console.log(row);
                this.idx = index;
                this.msg=row;//每一条数据的记录
                this.delarr.push(this.msg.PackingId);//把单行删除的每条数据的id添加进放删除数据的数组
                this.delVisible = true;
            },
            // 当批量删除的时候,如果要是没有选中,弹出提醒
            delWarnInfo() {
              this.$message('请选择您要删除的数据');
            },
            //批量删除
            delAll() {
                // alert("我进来啦~");
                var lengths = this.multipleSelection.length;
                
                for (let i = 0; i < lengths; i++) {
                  // console.log('aaaaaaaaaaaaaaaaaaaaaaaa');
                  console.log(this.multipleSelection[i]);
                  //this.multipleSelection[i].deleteStatus = '2';
                  this.api({
                    url: "/department/deleteDepartment",
                    method: "post",
                    data: this.multipleSelection[i]
                }).then(() => {
                  // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                  if(this.search == ""){
                    // alert("我不空啊")
                    this.getList();
                  }
                  else{
                    // alert("我怎么就空了呢？")
                    this.getListBySearch(this.search);
                  }
                }).catch(() => {
                  this.$message.error("删除失败")
                })
                
                }
                this.delVisibleByBatch = false;//关闭删除提示模态框
            },
            
             // 确定删除
            deleteRow(){
                let _vue = this;
                // 写自己的删除的对象
                // console.log(this.delarr)
                console.log("_vue.list:");
                console.log(_vue.list);
                console.log("_vue.index:"+_vue.idx);
                let rowItem = _vue.list[_vue.idx];
                //rowItem.deleteStatus = '2';
                console.log("rowItem:");
                console.log(rowItem);
                _vue.api({
                  url: "/department/deleteDepartment",
                  method: "post",
                  data: rowItem
                }).then(() => {
                  console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                  if(this.search == ""){
                    _vue.getList();
                  }
                  else{
                    // alert("我怎么就空了呢？")
                    _vue.getListBySearch(this.search);
                  }
                }).catch(() => {
                  _vue.$message.error("删除失败")
                })
                // user.deleteStatus = '2';
                // _vue.api({
                //   url: "/user/updateUser",
                //   method: "post",
                //   data: user
                // }).then(() => {
                //   _vue.getList()
                // }).catch(() => {
                //   _vue.$message.error("删除失败")
                // })
                this.delVisible = false;//关闭删除提示模态框
            },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      delSelect(){
        const length = this.multipleSelection.length;
        if(length == 0){
          this.delWarnInfo();
        }else{
          this.delVisibleByBatch = true;//显示删除弹框
        }
        // this.delAll();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection);
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 1) {
          return 'warning-row';
        } else if (rowIndex % 2 === 0) {
          // return 'success-row';
        }
        return '';
      },
      //实时搜索输入的内容
      querySearch(queryString, cb) {
        var staffLists = this.staffList2;
        var results = queryString ? staffLists.filter(this.createFilter(queryString)) : staffLists;
        // 调用 callback 返回建议列表的数据
        console.log(results)
        cb(results);
      },
      createFilter(queryString) {
        return (staff) => {
          return (staff.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelect(item) {
        this.tempDepartment.staffId = item.userId;
        //console.log("item", item);
      },
      handlerDepartment(){
        console.log("gggggg");
        console.log("departmentName:",this.tempDepartment.departmentName);
        // return;
        this.api({
          url: "/department/getDepartmentByName",
          method: "get",
          params: this.tempDepartment
        }).then(data => {
          console.log("data:",data);
          if(data === "fail"){
            // alert("无效");
            this.displayInfoFromBack = true;
            this.infoFromBack = "无效";
            this.enableCreate = true;
          }
          else{
            this.displayInfoFromBack = false;
            this.infoFromBack = "";
            this.enableCreate = false;
          }
          
        })
      },
      getList() {
        //查询列表
        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.api({
          url: "/department/listDepartment",
          method: "get",
          params: this.listQuery
        }).then(data => {
          console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
          console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },
      getAllUsers() {
        //获取员工列表
        this.api({
          url: "/user/list",
          method: "get"
        }).then(data => {
          console.log("allUser:",data)
          this.staffList = data.list;
          console.log('user:', this.staffList);

          //提供给实时搜索
          //console.log("data.length: ",data.list.length);
          for(var i = 0 ; i < data.list.length ; i++){
              var temp = data.list[i];
              temp['id_nickname'] = data.list[i]['userId']+'-'+data.list[i]['username'];
              console.log('temp:', temp);
              this.staffList2.push(temp);
          }
          //console.log('staffList2:', this.staffList2);
          var json = JSON.parse(JSON.stringify(data.list).replace(/id_nickname/g,"value"));
          this.staffList2 = json;
          console.log('staffList2:', this.staffList2);
        })
      },
      getUserName(id) {
        for(var i = 0 ; i < this.staffList.length ; i++){
              if(this.staffList[i]['userId'] === id){
                 return this.staffList[i]['username'];
              }
        }
        return "";
      },
      getAllDepartments() {
        //获取部门列表
        this.api({
          url: "/department/listDepartment",
          method: "get"
        }).then(data => {
          //this.departmentList = data.list;
          var temp_list = [];
          if(data.list.length>0){
            //var temp = data.list[0];
            var temp = Object.assign({}, data.list[0]);
            temp["department_id"] = "";
            temp["department_name"] = "无";
            temp["create_time"] = "";
            temp["department_desc"] = "";
            temp["staff_id"] = "";
            temp["superior_id"] = "";
            temp_list.push(temp);
          }
          this.departmentList = temp_list.concat(data.list);
          console.log(this.departmentList.length);
          console.log('departments:', this.departmentList);
        })
      },
      getListByOrderContent(){
        //查询列表

        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.api({
          url: "/department/listDepartmentByOrder",
          method: "get",
          params: this.listQuery
        }).then(data => {
          // console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
          // console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },

      // 当搜索框中有内容的时候，排序的时候需要只排序搜索出来的内容
      getListByContentHaveSearch(){
        //查询列表

        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.listQuery.value = this.search;
        this.api({
          url: "/department/listDepartmentByContentHaveSearch",
          method: "get",
          params: this.listQuery
        }).then(data => {
          console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
          console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },

      getListByOrderCreateTimeHaveSearch(){
        //查询列表

        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.listQuery.value = this.search;
        this.api({
          url: "/department/getListByOrderCreateTimeHaveSearch",
          method: "get",
          params: this.listQuery
        }).then(data => {
          console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
          console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },
      getListByOrderCreateTime(){
        //查询列表

        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.api({
          url: "/department/listDepartmentByOrderCreateTime",
          method: "get",
          params: this.listQuery
        }).then(data => {
          console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
          console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.tables = data.list;
          this.totalCount = data.totalCount;
        })
      },

      getListBySearch(val) {
        // console.log("val:"+val);
        //查询列表
        if (!this.hasPerm('article:list')) {
          return
        }
        this.listLoading = true;
        this.listQuery.value = val;
        // console.log(this.listQuery);
        this.api({
          url: "/department/listDepartmentBySearch",
          method: "get",
          params: this.listQuery
        }).then(data => {
          // console.log(data)
          this.listLoading = false;
          this.list = data.list;
          this.totalCount = data.totalCount;
        })
      },
      handleSizeChange(val) {
        //改变每页数量
        // alert("handleSizeChange()")
        this.listQuery.pageRow = val
        this.generalFun();
        // this.handleFilter();
      },
      handleCurrentChange(val) {
        //改变页码
        

        console.log("sortby:",this.listQuery.sortby)
        console.log("order:",this.listQuery.order)
        this.listQuery.pageNum = val
        this.generalFun();
        
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
      },
      showCreate() {
        //显示新增对话框
        this.tempDepartment.departmentName = "";
        this.tempDepartment.departmentDesc = "";
        this.tempDepartment.staffNickname = "";
        this.tempDepartment.superiorId = "";
        this.tempDepartment.staffId = "";
        this.dialogStatus = "create";
        this.dialogFormVisible = true

        this.infoFromBack = '';
        this.displayInfoFromBack = false;
        this.enableCreate = false
      },
      showDisplay(){
        this.dialogStatus = "dispalyAtt"
        this.dialogFormVisible = true
      },
      showUpdate($index) {
        //显示修改对话框
        //绑定相应的id
        this.tempDepartment.departmentId = this.list[$index].department_id;
        //绑定相应的内容
        this.tempDepartment.departmentName = this.list[$index].department_name;
        this.tempDepartment.departmentDesc = this.list[$index].department_desc;
        this.tempDepartment.staffId = this.list[$index].staff_id;
        this.tempDepartment.staffNickname = this.list[$index].staff_id+'-'+this.getUserName(this.list[$index].staff_id);
        this.tempDepartment.superiorId = this.list[$index].superior_id;
        this.dialogStatus = "update"
        this.dialogFormVisible = true

        this.infoFromBack = '';
        this.displayInfoFromBack = false;
        this.enableCreate = false
      },
      createDepartment() {
        //保存新部门
        this.tempDepartment.loginUserId = this.userId;
        console.log("tempDepartment.superiorId:", this.tempDepartment.superiorId)
        if(this.tempDepartment.superiorId == "" || this.tempDepartment.superiorId == "无"){
          console.log('1111:');
          this.tempDepartment.superiorId = null;
        }        
        //return;
        this.api({
          url: "/department/addDepartment",
          method: "post",
          data: this.tempDepartment
        }).then(() => {
          //console.log("test_20190324")
          let msg = "添加成功";
          this.dialogFormVisible = false;
          this.$message({
            message: msg,
            type: 'success',
            duration: 1 * 1000,
            onClose: () => {
              this.getList();
            }
          })

          //this.getList();
          //this.dialogFormVisible = false
        })
      },
      updateDepartment() {
        this.tempDepartment.loginUserId = this.userId;
        if(this.tempDepartment.superiorId == "" || this.tempDepartment.superiorId == "无"){
          console.log('1111:');
          this.tempDepartment.superiorId = null;
        }      
        console.log("tempDepartment:");
        console.log(this.tempDepartment);
        //修改文章
        this.api({
          url: "/department/updateDepartment",
          method: "post",
          data: this.tempDepartment
        }).then(() => {
          let msg = "修改成功";
          this.dialogFormVisible = false;
          this.$message({
            message: msg,
            type: 'success',
            duration: 1 * 1000,
            onClose: () => {
              this.getList();
            }
          })
        })
      },

      generalFun(){
        if(this.search){
          if(this.listQuery.sortby == "" & this.listQuery.order == ""){
            this.getListBySearch(this.search);
          }
          else if(this.listQuery.sortby == "content" && this.listQuery.order == "ASC"){
            // alert("你好啊")
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "ASC";
            this.getListByContentHaveSearch();
          }
          else if(this.listQuery.sortby == "content" && this.listQuery.order == "DESC"){
            // alert("很好啊")
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "DESC";
            this.getListByContentHaveSearch();
          }
          else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "ASC";
            this.getListByOrderCreateTimeHaveSearch();
          }
          else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "DESC";
            this.getListByOrderCreateTimeHaveSearch();
          }
          else{
            // ...
          }
        }
        // 没有搜索内容，所以可以直接
        else{
          // alert("ssssssssssssssssss")
          // console.log(this.prop);
          // console.log(this.order);
          if(this.listQuery.sortby == "" & this.listQuery.order == ""){
            
            this.getList();
          }
          else if(this.listQuery.sortby == "content" && this.listQuery.order == "ASC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "ASC";
            // ...
            this.getListByOrderContent();
          }
          else if(this.listQuery.sortby == "content" && this.listQuery.order == "DESC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "DESC";
            this.getListByOrderContent();
          }
          else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "ASC";
            this.getListByOrderCreateTime();
          }
          else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC"){
            // this.listQuery.sortby = this.prop;
            // this.listQuery.order = "DESC";
            this.getListByOrderCreateTime();
          }else{
            // ...
            this.getList();
            // alert("我是空的！")
          }
        }
      }
    }

  }
</script>


<style>
.el-table .warning-row {
    background:whitesmoke;
    
     /* background: #ffffff; */
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  
  .pagination{
    background-color:lavender;
    margin-right: 0%;
    text-align: right;
  }

  .searchWord .add1{
    display: inline;
  }

  #btn{
            /* padding: 5px 10px;
            background: #00b0f0;
            color: #FFF;
            border: none;
            border-radius: 5px; */
        }


</style>